import axios from "axios"
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse,InternalAxiosRequestConfig } from 'axios'
import { ServiceRequestConfig } from './type'


class ServiceRequest{
  instance: AxiosInstance
  constructor(config:ServiceRequestConfig){
    this.instance = axios.create(config)

    // 每个instance实例都添加拦截器
    this.instance.interceptors.request.use((config)=>{
      console.log('全局请求成功拦截')
      return config
    },err =>{
      // 全局请求失败拦截
      return err
    })
    this.instance.interceptors.response.use((res)=>{
      console.log('全局响应成功拦截')
      return res.data
    },err =>{
      return err
    })

    // 针对特定实例进行拦截
    this.instance.interceptors.request.use(
      config.interceptors?.requestSuccessFn as (value: InternalAxiosRequestConfig<any>) => InternalAxiosRequestConfig<any>,
      config.interceptors?.requestFailureFn
    )
    this.instance.interceptors.response.use(
      config.interceptors?.responseSuccessFn,
      config.interceptors?.responseFailureFn
    )
  }

  // 封装网络请求
  request<T = any>(config:ServiceRequestConfig<T>){
    // 单次请求成功拦截
    if(config.interceptors?.requestSuccessFn){
      config = config.interceptors.requestSuccessFn(config)
    }
    return new Promise<T>((resolve,reject) =>{
      this.instance.request<any,T>(config).then(res =>{
        // 单次响应成功拦截处理
        if(config.interceptors?.responseSuccessFn){
          res = config.interceptors.responseSuccessFn(res)
        }
        resolve(res)
      }).catch(err =>{
        reject(err) 
      })
    })
    // return this.instance.request(config)
  }
  get<T = any>(config:ServiceRequestConfig<T>){
    return this.request({...config,method:'GET'})
  }
  post<T = any>(config:ServiceRequestConfig<T>){
    return this.request({...config,method:'POST'})
  }
  delete<T = any>(config:ServiceRequestConfig<T>){
    return this.request({...config,method:'DELETE'})
  }
  patch<T = any>(config:ServiceRequestConfig<T>){
    return this.request({...config,method:'PATCH'})
  }
}

export default ServiceRequest